package de.dlrg.wms.gui.views;

import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;

import de.dlrg.wms.controller.controllers.DisciplineController;
import de.dlrg.wms.gui.FormContainer;
import de.dlrg.wms.gui.forms.DisciplineForm;
import de.dlrg.wms.gui.forms.generic.AbstractTableViewWithDeleteEdit;
import de.dlrg.wms.gui.views.coulmnNames.DisciplineColumns;
import de.dlrg.wms.model.Discipline;

import static de.dlrg.wms.gui.views.coulmnNames.DisciplineColumns.*;

public class DisciplineTableView extends AbstractTableViewWithDeleteEdit {
	private DisciplineController disciplineController;

	@Override
	public void refresh() {
		this.table.clearAll();
		this.table.setItemCount(0);

		List<Discipline> disciplines = this.disciplineController.readAll();
		for (Discipline discipline : disciplines) {
			TableItem disciplineTableItem = new TableItem(this.table, SWT.NULL);

			disciplineTableItem.setData(discipline);
			disciplineTableItem.setText(ID_COLUMN.ordinal(), "" + discipline.getId());
			disciplineTableItem.setText(NAME_COLUMN.ordinal(), "" + discipline.getName());
			disciplineTableItem.setText(DESCRIPTION_COLUMN.ordinal() , "" + discipline.getDescription());

		}
	}

	@Override
	public void editPressed() {
		Discipline selectedDiscipline = (Discipline) table.getSelection()[0]
				.getData();
		FormContainer formContainer = new FormContainer();
		formContainer.createContents();
		DisciplineForm disciplineForm = new DisciplineForm(
				formContainer.getComposite(), SWT.BORDER, disciplineController,
				formContainer.getShell(), selectedDiscipline);
		disciplineForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		disciplineForm.getClosing().addObserver(formContainer);
		formContainer.open();
		
		refresh();
	}


	@Override
	protected void deletePressed() {
		MessageBox messageBox = new MessageBox(shell,
				SWT.ICON_INFORMATION | SWT.OK | SWT.CANCEL);
		messageBox.setMessage("Do you want to delete "
				+ table.getSelectionCount() + " discipline(s)");
		int rc = messageBox.open();

		switch (rc) {
		case SWT.OK:
			break;
		default:
			return;
		}

		for (TableItem tableItem : table.getSelection()) {
			Discipline toDelete = (Discipline) tableItem.getData();
			disciplineController.delete(toDelete);
		}
	}

	public DisciplineTableView(Composite parent, int border,
			final DisciplineController disciplineController, final Shell shell) {
		super(parent, border);
		this.disciplineController = disciplineController;
		this.tableColumns = DisciplineColumns.class;
		this.initGUI(shell);
	}
}
